
package com.yuan.control;

import com.yuan.hibernate.HibernateSessionFactory;
import com.yuan.hibernate.月度考勤表;
import com.yuan.hibernate.月度考勤表DAO;
import com.yuan.hibernate.考勤表;
import com.yuan.hibernate.考勤表DAO;
import com.yuan.util.TimeUtil;

import org.hibernate.Transaction;

import java.util.List;

public class CheckControl {
    private 考勤表DAO m考勤表DAO = null;
    private 月度考勤表 m月度考勤表 = null;
    private 月度考勤表DAO m月度考勤表DAO = null;
    private volatile static CheckControl sInstance;

    private CheckControl() {
        m考勤表DAO = new 考勤表DAO();
        m月度考勤表DAO = new 月度考勤表DAO();
    }

    public static CheckControl getInstance() {
        if (sInstance == null) {
            synchronized (CheckControl.class) {
                if (sInstance == null) {
                    sInstance = new CheckControl();
                }
            }
        }
        return sInstance;
    }

    @SuppressWarnings("unchecked")
    public void update月度考勤表(String name, String team) {
        // 统计出勤次数
        int mCount = 0;
        String yearmonth = TimeUtil.getNowTime().substring(0, 6);
        List<考勤表> m考勤表List = m考勤表DAO.findBy职工姓名(name);
        for (考勤表 temp : m考勤表List) {
            if (temp.getId().get日期().startsWith(yearmonth)) {
                mCount++;
            }
        }

        // 查看是第一次插入还是更新数据
        Transaction tx = HibernateSessionFactory.getSession()
                .beginTransaction();
        List<月度考勤表> m月度考勤表List = m月度考勤表DAO.findBy职工姓名(name);
        for (月度考勤表 temp : m月度考勤表List) {
            if (temp.get日期().equals(TimeUtil.getNowTimeYearMonth())) {
                temp.set出勤(mCount);
                m月度考勤表DAO.merge(temp);
                tx.commit();
                return;
            }
        }
        m月度考勤表 = new 月度考勤表();
        m月度考勤表.set出勤(mCount);
        m月度考勤表.set所属队室(team);
        m月度考勤表.set职工姓名(name);
        m月度考勤表.set日期(TimeUtil.getNowTimeYearMonth());
        m月度考勤表DAO.save(m月度考勤表);
        tx.commit();
    }
}
